package com.csf.controller;

import com.csf.config.likeKeyConfig;
import com.csf.entity.Event;
import com.csf.entity.SessionReplace;
import com.csf.event.EventProducer;
import com.csf.service.likeService;
import com.csf.util.CommunityActivation;
import com.csf.util.communityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class LikeController implements CommunityActivation {

    @Autowired
    private likeService likeService;

    @Autowired
    private SessionReplace sessionReplace;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(path = "like",method = RequestMethod.POST)
    @ResponseBody
    public String getLike(int entityType,int entityId,int userLikeId,Integer postId){
        int userId = sessionReplace.getUser().getId();
//        直接进行点赞
        likeService.addLike(entityType,entityId,userId,userLikeId);
//         查看点赞数量
        int likeCount = likeService.likeCount(entityType, entityId);

        int likeStatus = likeService.likeStatus(userId, entityType, entityId);

        if (likeStatus ==1){
            Event event = new Event()
                    .setTopic(TOPIC_LIKE)
                    .setEntityUserId(userLikeId)
                    .setEntityId(entityId)
                    .setEntityType(entityType)
                    .setUserId(sessionReplace.getUser().getId())
                    .setData("postId",postId);
            eventProducer.fireEvent(event);

        }

//        点赞会对热度帖子热度有影响
        if (entityType == ENTITY_TYPE_POST){
            String postKey = likeKeyConfig.getPostKey();
            redisTemplate.opsForSet().add(postKey,postId);
        }

//        通过map集合来返回结果
        Map<String,Object> map = new HashMap<>();
        map.put("likeCount",likeCount);
        map.put("likeStatus",likeStatus);
        return communityUtils.getJsonString(0,null,map);
    }
}
